package com.example.demo.controller;

import com.example.demo.entity.req.AddDeptRes;
import com.example.demo.entity.Result;
import com.example.demo.entity.req.UpdateDpetRes;
import com.example.demo.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;

    @GetMapping("/depts")

    //查询部门列表
    public Result getAllDepts() {
        try{
            return new Result().success(deptService.getAllDepts());
        }
        catch (Exception e){
            return new Result().error("查询失败");
        }
    }

    //根据ID删除部门数据
    @DeleteMapping("/deleteDeptById/{id}")
    public Result deleteDeptById(@PathVariable("id") Integer id) {
        try{
            if (id == null) {
                return new Result().error("参数错误");
            }
            int num = deptService.deleteDeptById(id);
            if (num > 0) {
                return new Result().success();
            } else {
                return new Result().error("部门不存在");
            }
        }
        catch (Exception e) {
            return new Result().error("删除失败");
        }
    }

    //添加部门数据
    @PostMapping("/addDept")
    public Result addDept(@RequestBody AddDeptRes apr) {
        try{
            if (apr == null) {
                return new Result().error("参数错误");
            }
            int num = deptService.addDept(apr);
            if (num > 0) {
                return new Result().success();
            } else {
                return new Result().error("部门已存在");
            }
        }
        catch (Exception e) {
            log.error(e.getMessage());
            return new Result().error("添加失败");
        }
    }

    //根据ID查询部门数据
    @GetMapping("/getDeptById/{id}")
    public Result getDeptById(@PathVariable("id") Integer id) {
        try{
            if (id == null) {
                return new Result().error("参数错误");
            }
            return new Result().success(deptService.getDeptById(id));
        }
        catch (Exception e) {
            return new Result().error("查询失败");
        }
    }

    //根据ID修改部门数据
    @PostMapping("/updateDept")
    public Result updateDeptById(@RequestBody UpdateDpetRes udr) {
        try{
            if (udr == null) {
                return new Result().error("参数错误");
            }
            int num = deptService.updateDept(udr);
            if (num > 0) {
                return new Result().success();
            } else {
                return new Result().error("部门不存在");
            }
        }
        catch (Exception e) {
            log.error(e.getMessage());
            return new Result().error("修改失败");
        }
    }


}
